package RadianceM.DistributionSystem.service.impl;

import RadianceM.DistributionSystem.dto.Authority;
import RadianceM.DistributionSystem.entity.CareerInfo;
import RadianceM.DistributionSystem.entity.Job;
import RadianceM.DistributionSystem.entity.User;
import RadianceM.DistributionSystem.mapper.CareerInfoMapper;
import RadianceM.DistributionSystem.mapper.DictionaryValueMapper;
import RadianceM.DistributionSystem.mapper.JobMapper;
import RadianceM.DistributionSystem.mapper.UserMapper;
import RadianceM.DistributionSystem.service.UserService;
import RadianceM.DistributionSystem.utils.TokenUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

	@Resource
	public TokenUtil tokenUtil;
	@Resource
	public CareerInfoMapper careerInfoMapper;
	@Resource
	public JobMapper jobMapper;
	@Resource
	public DictionaryValueMapper dictionaryValueMapper;

	@Override
	public Map<String,Object> loginByPassword(String username, String password) {
		User user = baseMapper.selectOne(new QueryWrapper<User>().eq("username", username));
		Map<String,Object> map = new HashMap<>();
		// 账号不存在
		if(user == null){
			map.put("status",201);
			return map;
		}
		// 效验加密密码
		if(!Objects.equals(user.getPassword(), password)){
			map.put("status",202);
			return map;
		}
		/*
		* 密码效验成功
		*  通过redis检查是否存在
		*    存在 --> 账户登陆过 --> 删除token,使得上一个登录者token失效
		* 添加新token
		* */
		if(tokenUtil.redisUtil.get(tokenUtil.getRedisTokenPrefix() + user.getId()) != null) {
			String token = String.valueOf(tokenUtil.redisUtil.get(tokenUtil.getRedisTokenPrefix() + user.getId()));
			if(!tokenUtil.logoutToken(token)){
				map.put("status",203);
				return map; // token清除失败
			}
		}

		// 存取用户身份信息
		map.put("status",200);
		map.put("token",tokenUtil.generateToken(user.getId(),user.getUsername()));

		if(user.getPersonId()!=null) map.put("authority", Authority.AUTHORITY_STUDENT);
		 else if(user.getOfficeId()==null) map.put("authority", Authority.AUTHORITY_MANAGER_NO_INIT);
		else {
			// office --> 判断是否为系统管理员
			CareerInfo careerInfo = careerInfoMapper.selectById(user.getOfficeId());
			List<Job> jobList = jobMapper.selectList(
					new QueryWrapper<Job>().eq("officer_id",careerInfo.getOfficerId())
			);
			for (Job job : jobList) {
				String jobType = dictionaryValueMapper.selectById(job.getDictionaryJobType()).getValue();
				if(Objects.equals(jobType, "系统管理员")) {
					map.put("authority",Authority.AUTHORITY_MANAGER);
					break;
				}
			}
			map.putIfAbsent("authority", Authority.AUTHORITY_OFFICER);
		}
		// 登陆成功
		return map;
	}
}
